package userHelp

import (
	myConfig "common/config"
	"common/helper"
	myredis "common/redis"
	"encoding/json"
	"fmt"
	"time"
)

/*
充值分成
*/
func GetRechargeShare(uid string, level int) float64 {
	var sqlSelect string = ""
	var disableRechargeShare float64 = 0.00
	if level == 1 {
		sqlSelect = fmt.Sprintf("select disable_recharge_share_lv1 from tbl_member_return where uid=%s", uid)
	} else if level == 2 {
		sqlSelect = fmt.Sprintf("select disable_recharge_share_lv2 from tbl_member_return where uid=%s", uid)
	} else if level == 3 {
		sqlSelect = fmt.Sprintf("select disable_recharge_share_lv3 from tbl_member_return where uid=%s", uid)
	} else {
		return 0.0
	}

	err := g_sql.Get(&disableRechargeShare, sqlSelect)
	if err != nil {
		helper.SqlErrLog("AddDisableRechargeShare: sql:%s,reason:%s", sqlSelect, err.Error())
	}
	return disableRechargeShare
}

func ParentShare(uid string, ParentId string, orderId string, rechargeAmount float64, hiddenAmount float64, level int, firstCharge int) {
	if ParentId == "0" {
		return
	}

	WagedReq := myConfig.GetGameCfgFloat64(myConfig.CfgRechargeShareWagedReq)
	var validUser bool = false

	if GetTotalWaged(uid) >= WagedReq {
		validUser = true
	}

	sqlSelect := fmt.Sprintf("select rate from tbl_cfg_recharge_share_rate where level = %d", level)
	var lvRate float64 = 0.00
	var lvShare float64 = 0.00
	g_sql.Get(&lvRate, sqlSelect)
	lvShare = (rechargeAmount - hiddenAmount) * lvRate

	//插入分成记录
	if validUser {
		sqlInsert := fmt.Sprintf("insert into tbl_rec_recharge_share(uid,nickname,parent_id,amount,hidden_amount,level,recharge_rate,recharge_share,create_at,state,orderId,first_charge)"+
			"values(%s,'%s',%s,%0.2f,%0.2f,%d,%0.3f,%0.3f,%d,1,'%s',%d)", uid, GetMemberName(uid), ParentId, rechargeAmount, hiddenAmount, level, lvRate, lvShare, time.Now().Unix(), orderId, firstCharge)
		myredis.AddLogToRedis(sqlInsert)
		AddEnableRechargeShare(ParentId, level, lvShare)
		AutoRechargeShare(uid, ParentId, lvShare, level)

		helper.InfoLog("ParentShare %s", sqlInsert)
	} else {
		sqlInsert := fmt.Sprintf("insert into tbl_rec_recharge_share(uid,nickname,parent_id,amount,hidden_amount,level,recharge_rate,recharge_share,create_at,state,orderId,first_charge)"+
			"values(%s,'%s',%s,%0.2f,%0.2f,%d,%0.3f,%0.3f,%d,0,'%s',%d)", uid, GetMemberName(uid), ParentId, rechargeAmount, hiddenAmount, level, lvRate, lvShare, time.Now().Unix(), orderId, firstCharge)
		myredis.AddLogToRedis(sqlInsert)

		helper.InfoLog("ParentShare %s", sqlInsert)
		AddDisableRechargeShare(uid, level, lvShare)
	}
}

type ShareRate struct {
	Level int     `json:"level"`
	Rate  float64 `json:"rate"`
}

func GetUserShareRate(jsonString string, level int) (float64, error) {
	var shareRates []ShareRate
	var lvRate float64
	// 解析 JSON 字符串
	err := json.Unmarshal([]byte(jsonString), &shareRates)
	if err != nil {
		return lvRate, fmt.Errorf("无法解析 JSON 字符串: %v", err)
	}
	if len(shareRates) > 0 {
		for _, rate := range shareRates {
			if rate.Level == level {
				lvRate = rate.Rate
			}
		}
	}
	return lvRate, nil
}

func ParentSharePersonCfg(uid string, ParentId string, orderId string, rechargeAmount float64, hiddenAmount float64, level int, firstCharge int) {
	var lvShare float64
	var lvRate float64
	var err error
	if firstCharge == 1 {
		lvRate, err = GetUserShareRate(G_UserButton.GetRechargeShareRate(ParentId), level)
	} else {
		lvRate, err = GetUserShareRate(G_UserButton.GetRRechargeShareRateF(ParentId), level)
	}

	if err != nil {
		return
	}

	lvShare = (rechargeAmount - hiddenAmount) * lvRate
	//插入分成记录
	sqlInsert := fmt.Sprintf("insert into tbl_rec_recharge_share(uid,nickname,parent_id,amount,hidden_amount,level,recharge_rate,recharge_share,create_at,state,orderId,first_charge)"+
		"values(%s,'%s',%s,%0.2f,%0.2f,%d,%0.3f,%0.3f,%d,1,'%s',%d)", uid, GetMemberName(uid), ParentId, rechargeAmount, hiddenAmount, level, lvRate, lvShare, time.Now().Unix(), orderId, firstCharge)

	helper.InfoLog("ParentSharePersonCfg sqlInsert:%s", sqlInsert)
	myredis.AddLogToRedis(sqlInsert)
	AddEnableRechargeShare(ParentId, level, lvShare)
	AutoRechargeShare(uid, ParentId, lvShare, level)
}

/*
充值上下级分成
*/
func RechargeShare(uid string, amount float64, hiddenAmount float64, orderId string, level int, firstCharge int) {
	TotalDeposit := GetTotalDeposit(uid)
	helper.InfoLog("RechargeParenShare")
	if myConfig.IsActiveOpen(myConfig.ActiveType_RechargeShare) == 0 {
		return
	}

	if myConfig.GetGameCfgInt(myConfig.CfgRechargeShareType) == 0 {
		return
	}

	if myConfig.GetGameCfgInt(myConfig.CfgRechargeShareType) == 1 && TotalDeposit > 0.0 {
		return
	}

	if myConfig.GetGameCfgInt(myConfig.CfgRechargeShareType) == 2 && TotalDeposit == 0.0 {
		return
	}
	switch level {
	case 1:
		ParentShare(uid, GetProxyParentId(uid), orderId, amount, hiddenAmount, level, firstCharge)
	case 2:
		ParentShare(uid, GetProxyGrandId(uid), orderId, amount, hiddenAmount, level, firstCharge)
	case 3:
		ParentShare(uid, GetProxyGreatGrandId(uid), orderId, amount, hiddenAmount, level, firstCharge)
	}

}

func ClearEnableRechargeShare(uid string, level int) {
	var sqlUpdate string = ""
	if level == 1 {
		sqlUpdate = fmt.Sprintf("update tbl_member_return set enable_recharge_share_lv1=0.00 where uid=%s", uid)
	} else if level == 2 {
		sqlUpdate = fmt.Sprintf("update tbl_member_return set enable_recharge_share_lv2=0.00 where uid=%s", uid)
	} else if level == 3 {
		sqlUpdate = fmt.Sprintf("update tbl_member_return set enable_recharge_share_lv3=0.00 where uid=%s", uid)
	} else {
		return
	}

	_, err := g_sql.Exec(sqlUpdate)
	if err != nil {
		helper.SqlErrLog("AddDisableRechargeShare: sql:%s,reason:%s", sqlUpdate, err.Error())
	}
}

func AddEnableRechargeShare(uid string, level int, RechargeShare float64) {
	if RechargeShare == 0.00 {
		return
	}
	var sqlUpdate string = ""
	if level == 1 {
		sqlUpdate = fmt.Sprintf("update tbl_member_return set enable_recharge_share_lv1= enable_recharge_share_lv1 + %0.2f where uid=%s",
			RechargeShare, uid)
	} else if level == 2 {
		sqlUpdate = fmt.Sprintf("update tbl_member_return set enable_recharge_share_lv2= enable_recharge_share_lv2 + %0.2f where uid=%s",
			RechargeShare, uid)
	} else if level == 3 {
		sqlUpdate = fmt.Sprintf("update tbl_member_return set enable_recharge_share_lv3 = enable_recharge_share_lv3 + %0.2f where uid=%s",
			RechargeShare, uid)
	} else {
		return
	}

	_, err := g_sql.Exec(sqlUpdate)
	if err != nil {
		helper.SqlErrLog("AddDisableRechargeShare: sql:%s,reason:%s", sqlUpdate, err.Error())
	}
}

func ClearDisableRechargeShare(uid string, level int) {
	var sqlUpdate string = ""
	if level == 1 {
		sqlUpdate = fmt.Sprintf("update tbl_member_return set disable_recharge_share_lv1=0.00 where uid=%s", uid)
	} else if level == 2 {
		sqlUpdate = fmt.Sprintf("update tbl_member_return set disable_recharge_share_lv2=0.00 where uid=%s", uid)
	} else if level == 3 {
		sqlUpdate = fmt.Sprintf("update tbl_member_return set disable_recharge_share_lv3=0.00 where uid=%s", uid)
	} else {
		return
	}

	_, err := g_sql.Exec(sqlUpdate)
	if err != nil {
		helper.SqlErrLog("AddDisableRechargeShare: sql:%s,reason:%s", sqlUpdate, err.Error())
	}
}

/*
自动领取
*/
func AutoRechargeShare(uid string, ParentId string, rechargeAmount float64, level int) {

	if G_UserButton.GetRechargeButton(ParentId) == 0 && myConfig.IsActiveOpen(myConfig.ActiveType_RechargeShare) == 0 {
		sqlInsert := fmt.Sprintf("update tbl_rec_recharge_share set state=2 where uid=%s and level=%d", uid, level)
		myredis.AddLogToRedis(sqlInsert)
		return
	}

	if rechargeAmount == 0.0 {
		return
	}

	CashType := helper.TransactionRechargeShareBonuslv1 + level - 1
	AddBalanceTransactionRecord(ParentId, rechargeAmount,
		CashType, "0", helper.GenId(), 0.00, "", "", 0)
	AddUserWageItem(ParentId, rechargeAmount, CashType)
	sqlInsert := fmt.Sprintf("update tbl_rec_recharge_share set state=1 where uid=%s and level=%d and state=0", uid, level)
	myredis.AddLogToRedis(sqlInsert)
	AddUserBalanceByFloat64(ParentId, rechargeAmount)
	ClearEnableRechargeShare(ParentId, level)
	AddTotalRechargeShare(ParentId, rechargeAmount)

	_, errExec := g_sql.Exec("CALL tbl_report_proxy_change_update(?,?,?,?)", ParentId,
		CashType, rechargeAmount, time.Now().Unix())
	if errExec != nil {
		helper.GetloggerInstance().Emergencyf("CALL tbl_report_proxy_change_update(%s,%d,%0.2f,%d);	reason:%s",
			ParentId, CashType, rechargeAmount, time.Now().Unix(), errExec.Error())
	}

	_, errExec = g_sql.Exec("CALL tbl_report_user_change_update(?,?,?,?)", ParentId, CashType, rechargeAmount, time.Now().Unix())
	if errExec != nil {
		helper.GetloggerInstance().Emergencyf("CALL tbl_report_user_change_update(%s,%d,%0.2f,%d);	reason:%s",
			ParentId, CashType, rechargeAmount, time.Now().Unix(), errExec.Error())
	}

	return
}

func AddDisableRechargeShare(uid string, level int, RechargeShare float64) {
	var sqlUpdate string = ""
	if level == 1 {
		sqlUpdate = fmt.Sprintf("update tbl_member_return set disable_recharge_share_lv1=disable_recharge_share_lv1+%0.2f where uid=%s",
			RechargeShare, uid)
	} else if level == 2 {
		sqlUpdate = fmt.Sprintf("update tbl_member_return set disable_recharge_share_lv2=disable_recharge_share_lv2+%0.2f where uid=%s",
			RechargeShare, uid)
	} else if level == 3 {
		sqlUpdate = fmt.Sprintf("update tbl_member_return set disable_recharge_share_lv3=disable_recharge_share_lv3+%0.2f where uid=%s",
			RechargeShare, uid)
	} else {
		return
	}

	_, err := g_sql.Exec(sqlUpdate)
	if err != nil {
		helper.SqlErrLog("AddDisableRechargeShare: sql:%s,reason:%s", sqlUpdate, err.Error())
	}
}

func RechargeParenShare(uid, parentId string, orderId string, amount float64, hiddenAmount float64, level int, firstCharge int) {
	helper.InfoLog("RechargeParenShare")
	TotalDeposit := GetTotalDeposit(uid)

	// 获取个人分成奖励类型
	rechargeShareType := G_UserButton.GetRechargeShareType(parentId)
	// 不满足条件直接返回
	if (rechargeShareType == 0) || (rechargeShareType == 1 && TotalDeposit > 0.0) || (rechargeShareType == 2 && TotalDeposit == 0.0) {
		return
	}
	switch level {
	case 1:
		ParentSharePersonCfg(uid, GetProxyParentId(uid), orderId, amount, hiddenAmount, level, firstCharge)
	case 2:
		ParentSharePersonCfg(uid, GetProxyGrandId(uid), orderId, amount, hiddenAmount, level, firstCharge)
	case 3:
		ParentSharePersonCfg(uid, GetProxyGreatGrandId(uid), orderId, amount, hiddenAmount, level, firstCharge)
	}

}
